from typing import TYPE_CHECKING
import pandas as pd
from loguru import logger
from ui.components.composite.table import TgTable
from ui.components.dialogs.kline_dialog import KlineDialog

if TYPE_CHECKING:
    from ui.components.containers.layout import TgLayout


class BasisMonitorView:
    """基差监控View - 负责所有UI相关逻辑"""
    
    def __init__(self, layout: 'TgLayout', parent_widget):
        """
        初始化视图，创建并管理所有UI组件
        """
        self.layout = layout
        self.parent_widget = parent_widget
        self.index_table = None
        self.futures_table = None
        self._create_tables()
    
    def _create_tables(self):
        """创建并设置表格"""
        # 指数表格
        index_headers = ["代码", "名称", "价格", "涨跌额", "涨跌幅"]
        self.index_table = TgTable(
            headers=index_headers,
            data=[],
            editable=False,
            auto_height=True,
            max_height=500,
            highlight_on_selection=True
        )
        self._setup_index_table_styles()
        self.layout.addWidget(self.index_table)

        # 期货表格
        futures_headers = ["合约", "最新价格", "涨跌额", "涨跌幅", "到期日", "距离到期日", "基差点数", "年化基差"]
        self.futures_table = TgTable(
            headers=futures_headers,
            data=[],
            editable=False,
            auto_height=True,
            highlight_on_selection=True
        )
        self._setup_futures_table_styles()
        self.layout.addWidget(self.futures_table)

    def _setup_index_table_styles(self):
        """设置指数表格样式"""
        self.index_table.set_profit_loss_style("涨跌额", background_color=False, text_color=True, gradient=False)
        self.index_table.set_profit_loss_style("涨跌幅", background_color=False, text_color=True, gradient=False)
        
    def _setup_futures_table_styles(self):
        """设置期货表格样式"""
        self.futures_table.set_profit_loss_style("涨跌额", background_color=False, text_color=True, gradient=False)
        self.futures_table.set_profit_loss_style("涨跌幅", background_color=False, text_color=True, gradient=False)
        self.futures_table.set_profit_loss_style("基差点数", background_color=False, text_color=True, gradient=False)
        self.futures_table.set_profit_loss_style("年化基差", background_color=False, text_color=True, gradient=False)
    
    def update_index_table(self, data_df: pd.DataFrame):
        """更新指数表格数据"""
        try:
            self.index_table.update_data(data=data_df)
            logger.debug("Index table updated successfully")
        except Exception as e:
            logger.exception(f"Error updating index table: {e}")

    def update_futures_table(self, data_df: pd.DataFrame):
        """更新期货表格数据"""
        try:
            self.futures_table.update_data(data=data_df)
            logger.debug("Futures table with basis data updated successfully")
        except Exception as e:
            logger.exception(f"Error updating futures table: {e}")

    def get_index_table_cell_data(self, row: int, column: int) -> str:
        """获取指数表格单元格数据"""
        return self.index_table.get_cell_data(row, column)

    def get_futures_table_cell_data(self, row: int, column: int) -> str:
        """获取期货表格单元格数据"""
        return self.futures_table.get_cell_data(row, column)
    
    def show_chart_dialog(self, chart_type: str, symbol: str, history_service):
        """显示K线图对话框"""
        try:
            if chart_type == "index":
                logger.info(f"正在为指数 {symbol} 创建图表对话框...")
                dialog = KlineDialog(
                    symbol=symbol,
                    history_service=history_service,
                    show_minutes_buttons=False,
                    parent=self.parent_widget
                )
            elif chart_type == "futures":
                logger.info(f"正在为合约 {symbol} 创建图表对话框...")
                dialog = KlineDialog(
                    symbol=symbol,
                    history_service=history_service,
                    parent=self.parent_widget
                )
            else:
                return
            
            result = dialog.exec()
            logger.info(f"图表对话框已关闭，返回值: {result}")
            dialog.deleteLater()
            
        except Exception as e:
            logger.exception(f"显示K线图时出错: {e}")
    
    def connect_table_signals(self, index_callback, futures_callback):
        """连接表格信号"""
        self.index_table.cell_double_clicked.connect(index_callback)
        self.futures_table.cell_double_clicked.connect(futures_callback)